import { sysProfile, sysUser } from '@/api/user'
import router, { otherRoutes, constantRoutes, resetRouter } from '@/router'
// import router from '@/router'
const state = {
  token: '',
  userInfo: ''
}
const mutations = {
  SET_TOKEN(state, value) {
    state.token = value
  },
  SET_USERINFO(state, value) {
    state.userInfo = value
  },
  // 删除userInfo与token
  LOGOUT(state) {
    state.token = ''
    state.userInfo = ''
    // 重置路由
    resetRouter()
  }
}
const actions = {
  async getUserInfo(ctx) {
    const res = await sysProfile()
    const res2 = await sysUser(res.data.userId)
    // 合并对象
    // 最常见的：a:{...} b:{..}  {...a,...b}   Object.assign({},a,b,....)
    const res3 = Object.assign({}, res.data, res2.data)
    ctx.commit('SET_USERINFO', res3)

    // 数据匹配将匹配数据添加到路由中
    // 用户信息权限数据:res3.roles.menus
    // 动态路由：otherRoutes
    // 从动态路由中过滤出有权限的路由数据
    const newArr = otherRoutes.filter((item) => {
      return res3.roles.menus.includes(item.meta.name)
    })
    console.log('newArr', newArr)
    // addRoutes添加的路由并不是立马生效，是再经过一次导航守卫才生效
    newArr.push({ path: '*', redirect: '/404', hidden: true })
    router.addRoutes(newArr)
    // 手动更新this.$router.options.routes
    router.options.routes = [...constantRoutes, ...newArr]

    // console.log('用户信息', res)
    // console.log('用户信息2', res2)
    console.log(router.options.routes)
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
